<?php
/*
* Author: Jason ZHENG <zmj522008@hotmil.com>
* Date  : 2018/05/16
* Class : City
*/
namespace app\index\controller;

use think\Controller;
use think\Db;

/**
 * 三级联动地区
 */
class City extends Controller
{

	public function getCities()
	{
		$level1 = Db::table('address')->where(['levelType'=>1])->select();
		$level2 = Db::table('address')->where(['levelType'=>2])->select();
		$level3 = Db::table('address')->where(['levelType'=>3])->select();
		$provinces = [];
		foreach ($level1 as $k => $province) {
			$provinces[$k]['province'] = ['value' => $province['ID'], 'label' => $province['Name'] ];
			$cities = array_values(array_filter($level2, function($city) use($province) {return $city['ParentId'] == $province['ID']; } ) );
			
			$cities = array_map(function($c){return ['value'=>$c['ID'], 'label'=>$c['Name'] ];}, $cities);

			$provinces[$k]['province'] = array_merge($provinces[$k]['province'], ['children' => $cities]);
			foreach ($provinces[$k]['province']['children'] as $j => $city)
			{
				$towns = array_values(array_filter($level3, function($town) use($city) {return $town['ParentId'] == $city['value']; } ) );
				$towns = array_map(function($t){return ['value'=>$t['ID'], 'label'=>$t['Name'] ];}, $towns);
				$provinces[$k]['province']['children'][$j]['children'] = $towns;
			}

		}

		return ['code'=>666,'msg'=>'全国各省市区列表','data'=>$provinces];
	}

	public function getProvinces()
	{
		$level1 = Db::table('address')->where(['levelType'=>1])->select();
		$level2 = Db::table('address')->where(['levelType'=>2])->select();
		$provinces = [];
		foreach ($level1 as $k => $province) {
			$provinces[$k]['province'] = ['value' => $province['ID'], 'label' => $province['Name'] ];
			$cities = array_values(array_filter($level2, function($city) use($province) {return $city['ParentId'] == $province['ID']; } ) );
			
			$cities = array_map(function($c){return ['value'=>$c['ID'], 'label'=>$c['Name'] ];}, $cities);

			$provinces[$k]['province'] = array_merge($provinces[$k]['province'], ['children' => $cities]);

		}

		return ['code'=>666,'msg'=>'全国各省市区列表','data'=>$provinces];
	}
}